package com.warm.log.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.warm.auth.helper.LoginHelper;
import com.warm.core.enums.HttpMethod;
import com.warm.core.utils.JsonUtil;
import com.warm.core.utils.StringUtils;
import com.warm.core.utils.ip.IpUtils;
import com.warm.log.annotation.Log;
import com.warm.log.enums.BusinessStatus;
import com.warm.orm.domain.sys.SysOperLog;
import com.warm.system.api.LoginUser;
import com.warm.thread.manager.AsyncManager;
import com.warm.thread.manager.factory.AsyncFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.noear.solon.core.aspect.Interceptor;
import org.noear.solon.core.aspect.Invocation;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.UploadedFile;

import java.util.Collection;
import java.util.Map;

@Slf4j
public class LogInterceptor implements Interceptor {
    /**
     * 排除敏感属性字段
     */
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};

    @Override
    public Object doIntercept(Invocation inv) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Exception e = null;
        Object invoke = null;
        try {
            invoke = inv.invoke();
            return invoke;
        } catch (Exception ignored) {
            e = ignored;
            throw e;
        } finally {
            handleLog(inv, e, invoke, stopWatch);
        }
    }

    protected void handleLog(final Invocation inv, final Exception e, Object jsonResult
            , StopWatch stopWatch) {
        try {
            // 获取当前的用户
            LoginUser loginUser = LoginHelper.getN();
            Log log = inv.method().getAnnotation(Log.class);
            if (loginUser == null && !log.enableNoLogin()) {
                return;
            }

            // *========数据库日志=========*//
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = IpUtils.getIpAddr();
            operLog.setOperIp(ip);
            if (Context.current() !=null) {
                operLog.setOperUrl(StringUtils.substring(Context.current().path(), 0, 255));
                // 设置请求方式
                operLog.setRequestMethod(Context.current().method());
            }
            if (loginUser != null) {
                operLog.setOperName(loginUser.getUsername());
            }

            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = inv.target().getClass().getName();
            String methodName = inv.method().getMethod().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 处理设置注解上的参数
            getControllerMethodDescription(inv, operLog, jsonResult);
            stopWatch.stop();
            // 设置消耗时间
            operLog.setCostTime(stopWatch.getTime());
            // 保存数据库
            AsyncManager.execute(AsyncFactory.recordOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param inv     调用者
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(Invocation inv, SysOperLog operLog, Object jsonResult) throws Exception {
        Log log = inv.method().getAnnotation(Log.class);
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(inv, operLog, log.excludeParamNames());
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && ObjectUtil.isNotNull(jsonResult)) {
            operLog.setJsonResult(StringUtils.substring(JsonUtil.objectToJson(jsonResult), 0, 2000));
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(Invocation inv, SysOperLog operLog, String[] excludeParamNames) throws Exception {
        String requestMethod = operLog.getRequestMethod();
        if (Context.current() == null || MapUtil.isEmpty(Context.current().paramsMap())
                && (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))) {
            String params = argsArrayToString(inv.args(), excludeParamNames);
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        } else if (Context.current() != null && MapUtil.isNotEmpty(Context.current().paramsMap())) {
            operLog.setOperParam(StringUtils.substring(JsonUtil.stringify(Context.current().paramsMap()
                    , ArrayUtil.addAll(EXCLUDE_PROPERTIES, excludeParamNames)), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        String jsonObj = JsonUtil.stringify(o, ArrayUtil.addAll(EXCLUDE_PROPERTIES, excludeParamNames));
                        params.append(jsonObj).append(" ");
                    } catch (Exception ignored) {
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(UploadedFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof UploadedFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof UploadedFile;
            }
        }
        return o instanceof UploadedFile || o instanceof Context;
    }
}
